import store from 'store'
import headerView from  '../views/header.art'
import signupModles from '../models/http'

class head{
    constructor() {
        this.render()
        this.isSignin = false
        this.username = ''

    }
  async  render() {
        await this.auth()
        let html = headerView ({
            isSignin: this.isSignin,
            username: this.username
        })
        $('.page header').html(html)

        $('#register').on('click', function () {
            $('#login-view').css('display', 'block')
        })
        $('#login').on('click', function () {
            $('#login-view').css('display', 'block')

        })
        
     
        $('#btn2').on('click', this.handlefrom.bind(this, '/api/users/signup'))
        $('#btn1').on('click', this.handlefrom.bind(this, '/api/users/signin'))
    }
    async  handlefrom(url) {
        let data = $('.form-validate').serialize()
        let res = await signupModles.post({
            url,
            type: 'post',
            data: data
        })

        this.handlefromSucc(res)
    }


    async auth() {
        let result = await signupModles.post({
            url: '/api/users/isSignin'
        })
       

        let username = result.data.username
        this.isSignin = username ? true : false
        this.username = username
    }

    handlefromSucc(res) {
        if (res.data.issign) {
            let html = headerView({
                isSignin: true,
                username: res.data.username
            })
            $('.page header').html(html)
        } else {
            alert(res.data.message)
        }

        $('#logout').on('click', async function () {          
          /*   let result = await signupModles.post({
                url: '/api/users/signout',
            }) */
            store.remove('token')
               location.reload()
          
        })

    }
    
}

new head